﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using org.Alexander.EDAS;

namespace TestEDAS
{
    public class PackageProcessorTest
    {
        string src;

        public void PushDataTest()
        {
            PackageProcessor proc = new PackageProcessor();
            S s = new S();
            proc.Init(s);
            proc.AnalyzeLength = bs =>
            {
                if (bs.Length > 4)
                {
                    byte[] data = new byte[4];
                    for (int i = 0; i < 4; i++)
                    {
                        data[i] = bs[i];
                    }
                    int len = BitConverter.ToInt32(data, 0);
                    return len + 4;
                }
                else
                {
                    return 0;
                }
            };
            proc.PackageReceived += new Action<byte[], IWorkingSocket>(proc_PackageReceived);

            src = "我是测试数据";
            byte[] bytes = Encoding.UTF8.GetBytes(src);
            byte[] header = BitConverter.GetBytes(bytes.Length);

            MemoryStream pkgs = new MemoryStream();
            for (int i = 0; i < 10; i++)
            {
                pkgs.Write(header, 0, 4);
                pkgs.Write(bytes, 0, bytes.Length);
            }


            pkgs.Position = 0;

            for (int i = 0; i < 22; i++)
            {
                byte[] temp = new byte[10];
                pkgs.Read(temp, 0, 10);

                proc.PushData(temp, temp.Length);
            }


        }

        void proc_PackageReceived(byte[] arg1, IWorkingSocket arg2)
        {
            string s = Encoding.UTF8.GetString(arg1, 4, arg1.Length - 4);
            if (s != src)
            {
                throw new Exception("error string:" + s);
            }
        }
        
    }

    class S : IWorkingSocket
    {
        #region IWorkingSocket 成员

        public long ID
        {
            get;
            set;
        }

        public object SessionData
        {
            get;
            set;
        }

        public void SendWaitReceive(byte[] Data)
        {
            throw new NotImplementedException();
        }

        public void SendToQueue(byte[] Data)
        {
            throw new NotImplementedException();
        }

        public void WaitReceive()
        {
            throw new NotImplementedException();
        }

        public void Disconnect()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
